// ignore_for_file: use_build_context_synchronously

import 'package:flutter/material.dart';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';
import '../../../components/Search/Search.dart';
import '../../../store/dataList/data-list.dart';
import '../../../store/project/project.dart';
import '../../../util/git/git.dart';
import '../../content-layout.dart';

class GitViewWidget extends StatefulWidget {
  const GitViewWidget({super.key});

  @override
  State<GitViewWidget> createState() => _GitViewWidgetState();
}

class _GitViewWidgetState extends State<GitViewWidget> {
  String curPath = '';
  List<CommitLog> logList = [];
  List<Map<String, dynamic>> projects = [];

  @override
  void initState() {
    super.initState();
    loadProject();
  }

  loadProject() async {
    List<Map<String, dynamic>> data = await ProjectStore.getProjectList();

    setState(() {
      projects = data;
      if (projects.isNotEmpty) {
        curPath = projects[0]['path'];
        click(context);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ContentLayout(
      leftSlot: GitList(list: logList),
      rightSlot: const Text('data'),
      headerSlot: renderHeader,
    );
  }

  Future<void> click(BuildContext context) async {
    if (curPath == '') {
      showToast("请选择项目",
          animation: StyledToastAnimation.none,
          reverseAnimation: StyledToastAnimation.none,
          context: context);
      return;
    }
    try {
      final data = await getGitLogList(curPath);
      // 判断组件是否销毁
      if (!mounted) {
        return;
      }
      setState(() {
        logList = data;
      });
    } catch (e) {
      showToast((e as ArgumentError).message,
          animation: StyledToastAnimation.none,
          reverseAnimation: StyledToastAnimation.none,
          context: context);
    }
  }

  Widget get renderHeader {
    return Row(
      children: [
        const SearchWidget(),
        Row(
          children: [
            const SizedBox(width: 20),
            DropdownMenu<String>(
              initialSelection: curPath,
              width: 150,
              hintText: '选择项目',
              onSelected: (t) {
                setState(() {
                  curPath = t!;
                });
              },
              dropdownMenuEntries: _buildMenuList(projects
                  .map(
                      (e) => DataListItem(value: e['path']!, label: e['name']!))
                  .toList()),
            ),
            const SizedBox(width: 20),
            SizedBox(
              width: 100,
              height: 40,
              child: ElevatedButton(
                child: const Text('查询'),
                onPressed: () {
                  click(context);
                },
              ),
            )
          ],
        )
      ],
    );
  }
}

class GitList extends StatelessWidget {
  final List<CommitLog> list;
  const GitList({super.key, required this.list});

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      // padding: const EdgeInsets.all(8),
      itemCount: list.length,
      itemBuilder: (context, index) => Container(
          height: 80,
          width: double.infinity,
          margin: const EdgeInsets.only(bottom: 8),
          decoration: const BoxDecoration(
            color: Colors.white,
          ),
          child: Padding(
            padding: const EdgeInsets.all(10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  list[index].author,
                  style: const TextStyle(
                      fontWeight: FontWeight.w600,
                      fontSize: 18,
                      color: Color.fromRGBO(95, 107, 158, 1)),
                ),
                Text(
                  list[index].message,
                  style: const TextStyle(
                      fontWeight: FontWeight.w600,
                      fontSize: 16,
                      overflow: TextOverflow.ellipsis,
                      color: Color.fromRGBO(200, 200, 200, 1)),
                )
                // Expanded(child: Text('${list[index]["desc"]}'),)
              ],
            ),
          )),
    );
  }
}

List<DropdownMenuEntry<String>> _buildMenuList(List<DataListItem> data) {
  return data.map((DataListItem item) {
    return DropdownMenuEntry<String>(value: item.value, label: item.label);
  }).toList();
}

// Widget renderFormItem(String label, Widget slot) {
//   // return ;
// }